package com.goatrock.media.thisway.app.ui;

import com.goatrock.media.thisway.common.constants.ApplicationConstants;
import com.goatrock.media.thisway.common.exceptions.ServiceException;
import com.goatrock.media.thisway.domain.service.RetrievalService;
import com.goatrock.media.thisway.common.model.ApplicationConfig;
import com.goatrock.media.thisway.common.model.ShortcutRequest;
import com.goatrock.media.thisway.common.model.Title;
import com.goatrock.media.thisway.common.util.BeanLocator;
import com.goatrock.media.thisway.domain.service.ConfigDataService;
import com.goatrock.media.thisway.domain.service.InitializeAppService;
import com.goatrock.media.thisway.domain.service.ShortcutService;
import java.awt.Color;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.JFrame;
import javax.swing.UIManager;
import org.apache.log4j.Logger;

public class Main extends javax.swing.JFrame {
    private Logger logger = Logger.getLogger(Main.class);
    ConfigDataService configService;
    RetrievalService titleService;
    ShortcutService shortcutService;
    ShortcutRequest shortcutRequest = new ShortcutRequest();
    ApplicationConfig appConfig;
    InitializeAppService initAppService;
    ProcessingFrame pFrame = new ProcessingFrame();
    List<Title> titles;

    public Main() {
        
        logger.debug("starting program");
        initComponents();
        initAppBeans();
//        initApp();
        
//        final SplashScreen splash = SplashScreen.getSplashScreen();
//        if(splash != null){
//            try{
//                Thread.currentThread().sleep(10000);
//            }catch(Exception e){
//
//            }
//        }
        loadAppData();
        this.setLocationByPlatform(true);
        logger.debug("Program loaded.");
    }
    
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        panelMain = new javax.swing.JPanel();
        btnCreate = new javax.swing.JButton();
        btnOptions = new javax.swing.JButton();
        btnRefresh = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        listMovies = new javax.swing.JList();
        jPanel2 = new javax.swing.JPanel();
        cbCreateYears = new javax.swing.JCheckBox();
        cbCreateGenres = new javax.swing.JCheckBox();
        cbCreateNewMovies = new javax.swing.JCheckBox();
        newMoviesCB = new javax.swing.JComboBox();
        newMovesLbl1 = new javax.swing.JLabel();
        newMoviesLbl2 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        lblTotal = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("ThisWay");
        setBackground(new java.awt.Color(255, 255, 204));

        panelMain.setBackground(new java.awt.Color(255, 255, 204));

        btnCreate.setBackground(new java.awt.Color(204, 255, 102));
        btnCreate.setText("Create");
        btnCreate.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        btnCreate.setOpaque(false);
        btnCreate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCreateActionPerformed(evt);
            }
        });

        btnOptions.setBackground(new java.awt.Color(204, 255, 102));
        btnOptions.setText("Options");
        btnOptions.setOpaque(false);
        btnOptions.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOptionsActionPerformed(evt);
            }
        });

        btnRefresh.setBackground(new java.awt.Color(204, 255, 102));
        btnRefresh.setText("Refresh");
        btnRefresh.setOpaque(false);
        btnRefresh.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRefreshActionPerformed(evt);
            }
        });

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));
        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Movies", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 12), new java.awt.Color(0, 0, 0))); // NOI18N
        jPanel1.setOpaque(false);

        jScrollPane1.setViewportView(listMovies);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(19, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 224, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 433, Short.MAX_VALUE)
                .addContainerGap())
        );

        jPanel2.setBackground(new java.awt.Color(255, 255, 255));
        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Shortcut Configuration", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 12), new java.awt.Color(0, 0, 0))); // NOI18N
        jPanel2.setForeground(new java.awt.Color(102, 102, 255));
        jPanel2.setOpaque(false);

        cbCreateYears.setBackground(new java.awt.Color(255, 255, 255));
        cbCreateYears.setText("Create Years");
        cbCreateYears.setContentAreaFilled(false);

        cbCreateGenres.setBackground(new java.awt.Color(255, 255, 255));
        cbCreateGenres.setText("Create Genres");
        cbCreateGenres.setOpaque(false);

        cbCreateNewMovies.setBackground(new java.awt.Color(255, 255, 255));
        cbCreateNewMovies.setText("New Movies");
        cbCreateNewMovies.setOpaque(false);

        newMoviesCB.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" }));

        newMovesLbl1.setText("Within the last...");

        newMoviesLbl2.setText("...years");
        newMoviesLbl2.setToolTipText("");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(14, 14, 14)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(cbCreateGenres)
                    .addComponent(cbCreateYears)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addComponent(cbCreateNewMovies)
                                .addGap(51, 51, 51))
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addComponent(newMovesLbl1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                        .addComponent(newMoviesCB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(newMoviesLbl2)))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(cbCreateYears)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(cbCreateGenres)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(cbCreateNewMovies)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(newMoviesLbl2)
                    .addComponent(newMoviesCB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(newMovesLbl1))
                .addContainerGap(340, Short.MAX_VALUE))
        );

        jLabel2.setText("Total: ");

        lblTotal.setText("           ");

        javax.swing.GroupLayout panelMainLayout = new javax.swing.GroupLayout(panelMain);
        panelMain.setLayout(panelMainLayout);
        panelMainLayout.setHorizontalGroup(
            panelMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelMainLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(panelMainLayout.createSequentialGroup()
                        .addGroup(panelMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, panelMainLayout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(lblTotal))
                            .addComponent(btnOptions, javax.swing.GroupLayout.Alignment.LEADING))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 124, Short.MAX_VALUE)
                        .addComponent(btnRefresh))
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(18, 18, 18)
                .addGroup(panelMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnCreate))
                .addContainerGap())
        );
        panelMainLayout.setVerticalGroup(
            panelMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelMainLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(panelMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(lblTotal))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(panelMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnOptions)
                    .addComponent(btnRefresh)
                    .addComponent(btnCreate))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(panelMain, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(panelMain, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnOptionsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOptionsActionPerformed
        logger.debug("opening config window");
        ConfigurationWindow cw = new ConfigurationWindow();
        cw.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        cw.addWindowListener(new WindowListener(){
         public void windowClosing(WindowEvent e) {}
         public void windowClosed(WindowEvent e) {loadAppData();}
         public void windowIconified(WindowEvent e) {}
         public void windowDeiconified(WindowEvent e) {}
         public void windowOpened(WindowEvent e) {}
         public void windowActivated(WindowEvent e) {}
         public void windowDeactivated(WindowEvent e) {}
        });
        cw.setVisible(rootPaneCheckingEnabled);
    }//GEN-LAST:event_btnOptionsActionPerformed

    private void btnRefreshActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRefreshActionPerformed
        loadAppData();
    }//GEN-LAST:event_btnRefreshActionPerformed

    private void btnCreateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCreateActionPerformed
        toggleProcessingWindow(true);

        populateShortcutParameterObject();
        try{
            shortcutService.GenerateShortcutsByParameters(shortcutRequest, appConfig);
        }catch(ServiceException e){
            logger.error(e.getReturnMessage());
        }
        toggleProcessingWindow(false);
    }//GEN-LAST:event_btnCreateActionPerformed

    public void loadAppData(){
        toggleProcessingWindow(true);
        logger.info("Loading config locations");
        appConfig = configService.retrieveApplicationConfig();
        titles = titleService.getTitles(appConfig.getMediaLocations());
        if(titles != null){
            listMovies.setListData(titles.toArray());
        }

        lblTotal.setText(Integer.toString(titles.size()));
        toggleProcessingWindow(false);
    }

    public void toggleProcessingWindow(boolean flag){
        try{
            if(flag){
                    pFrame.setVisible(true);
                    int xLoc = (this.getWidth() / 2 - pFrame.getWidth() / 2)
                            +this.getLocationOnScreen().x;
                    int yLoc = (this.getHeight() / 2 - pFrame.getHeight() / 2)
                            +this.getLocationOnScreen().y;
                    pFrame.setLocation(xLoc, yLoc);
                    pFrame.paint(pFrame.getGraphics());
            }else{
                pFrame.dispose();
            }
        }catch(Exception e){
                //TO-DO: does anything really need to be done here
            }

    }

    public static void main(String args[]) {
        try{
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        }catch(Exception e){
            //TO-DO: log something here
        }

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Main().setVisible(true);
            }
        });
    }

    public void populateShortcutParameterObject(){
        Map paramMap = new HashMap();

        if(this.cbCreateGenres.isSelected()){
            paramMap.put(ApplicationConstants.CREATE_GENRES, ApplicationConstants.PARAM_USE);
        }
        if(this.cbCreateYears.isSelected()){
            paramMap.put(ApplicationConstants.CREATE_YEARS, ApplicationConstants.PARAM_USE);
        }
        if(this.cbCreateNewMovies.isSelected()){
            paramMap.put(ApplicationConstants.CREATE_NEW_MOVIES, ApplicationConstants.PARAM_USE);
            int startYear = Calendar.getInstance().get(Calendar.YEAR) - Integer.parseInt(this.newMoviesCB.getSelectedItem().toString());
            paramMap.put(ApplicationConstants.CREATE_NEW_MOVIES_START_YEAR, startYear);
        }

        shortcutRequest.setParameters(paramMap);
        shortcutRequest.setTitles(titles);
    }

    public void initAppBeans(){
        initAppService = (InitializeAppService)BeanLocator.getBean(ApplicationConstants.INIT_APP_SERVICE_BEAN);
        configService = (ConfigDataService)BeanLocator.getBean(ApplicationConstants.CONFIG_SERVICE_BEAN);
        titleService = (RetrievalService)BeanLocator.getBean(ApplicationConstants.RETRIEVAL_SERVICE_BEAN);
        shortcutService = (ShortcutService)BeanLocator.getBean(ApplicationConstants.SHORTCUT_SERVICE_BEAN);
    }

    public void initApp(){
        try {
            initAppService.InitializeAppComponents();
        } catch (ServiceException ex) {
            logger.error("**** Error initializing app ****"+ex.getReturnMessage());
            //TO-DO: display some message to the user that there was an issue and close the program.
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCreate;
    private javax.swing.JButton btnOptions;
    private javax.swing.JButton btnRefresh;
    private javax.swing.JCheckBox cbCreateGenres;
    private javax.swing.JCheckBox cbCreateNewMovies;
    private javax.swing.JCheckBox cbCreateYears;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblTotal;
    private javax.swing.JList listMovies;
    private javax.swing.JLabel newMovesLbl1;
    private javax.swing.JComboBox newMoviesCB;
    private javax.swing.JLabel newMoviesLbl2;
    private javax.swing.JPanel panelMain;
    // End of variables declaration//GEN-END:variables

    public ConfigDataService getConfigService() {
        return configService;
    }

    public void setConfigService(ConfigDataService configService) {
        this.configService = configService;
    }

    public RetrievalService getTitleService() {
        return titleService;
    }

    public void setTitleService(RetrievalService titleService) {
        this.titleService = titleService;
    }

    public Color getBGColor(){
        return Color.white;
    }
}
